package com.aliwo.rereflect;

import com.aliwo.Cat;

import java.lang.reflect.Method;

/**
 * .
 *
 * @author Xu Yayuan
 * @date 2022/2/20
 */
public class ReReflectQuestion3 {
    public static void main(String[] args) throws Exception {
        m1();
        m2();
        m3();

    }

    private static void m1() {
        Cat cat = new Cat();
        Long starttime = System.currentTimeMillis();
        for (int i = 0; i <100000000; i++ ) {
            cat.hi2();
        }
        Long endtime = System.currentTimeMillis();
        System.out.println("传统方式耗时:" + (endtime-starttime));
    }

    private static void m2() throws Exception {
        Class cls = Class.forName("com.aliwo.Cat");
        Object o = cls.newInstance();
        Method method = cls.getMethod("hi2");
        Long starttime = System.currentTimeMillis();
        for (int i = 0; i <100000000; i++ ) {
            method.invoke(o);
        }
        Long endtime = System.currentTimeMillis();
        System.out.println("反射耗时:" + (endtime-starttime));
    }

    private static void m3() throws Exception {
        Class cls = Class.forName("com.aliwo.Cat");
        Object o = cls.newInstance();
        Method method = cls.getMethod("hi2");
        Long starttime = System.currentTimeMillis();
        method.setAccessible(true); // 反射调用方法时，取消安全检查机制，提高运行效率
        for (int i = 0; i <100000000; i++ ) {
            method.invoke(o);
        }
        Long endtime = System.currentTimeMillis();
        System.out.println("反射调用方法时，取消安全检查机制:" + (endtime-starttime));
    }
}
